using System.Web.UI;
using Quiki.ExpressionParsers;

namespace Quiki.ElementFormatters
{
    public class InternalLinkElementFormatter : LambdaElementFormatter
    {
        public InternalLinkElementFormatter() : base(WikiTextElementType.InternalLink, CustomBeginAction, null)
        {
        }

        private static void CustomBeginAction(WikiTextElement element, HtmlFormatterContext context)
        {
            WikiInternalLinkElement internalLinkElement = (WikiInternalLinkElement) element;
            WikiDocReference reference = internalLinkElement.Reference;

            if (reference.IsCategory)
                return;

            string linkText;
            linkText = internalLinkElement.LinkText;

            if (internalLinkElement.Exists)
            {
                string url = ConvertWikiDocReferenceToUrl(reference, context);

                if (linkText == null)
                {
                    WikiDocument linkedDocument = context.DocumentGraph.FindDocument (reference);
                    linkText = linkedDocument.Title;
                }

                context.Writer.AddAttribute(HtmlTextWriterAttribute.Href, url);
                context.Writer.RenderBeginTag(HtmlTextWriterTag.A);
                context.Writer.Write(linkText);
                context.Writer.RenderEndTag();
            }
            else
            {
                if (linkText == null)
                    linkText = reference.LastPart;

                context.Writer.Write (linkText);
                context.Writer.Write(" <i>(TODO)</i>");
            }
        }

        private static string ConvertWikiDocReferenceToUrl(WikiDocReference reference, HtmlFormatterContext context)
        {
            return context.Document.PathToRoot + reference.ToUrl();
        }
    }
}